<!-- 订单列表 -->
<template>
  <div class="app-container">
    <div class="search-box">
      <el-form :model="listQuery" :inline="true">
        <el-form-item label="商品名称" placeholder="请输入商品名称">
          <el-input v-model="listQuery.shopName" maxlength="25" />
        </el-form-item>
        <el-form-item label="商品状态">
          <el-select v-model="listQuery.status" placeholder="请选择商品状态">
            <el-option label="全部" value="0" />
            <el-option label="上架" value="1" />
            <el-option label="下架" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="onScretSubmit">查询</el-button>
          <el-button type="primary" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="function">
      <el-button type="danger" size="small" @click="clickAdd"
        >新增</el-button
      >
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="ID" width="60">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="商品名称">
        <template slot-scope="scope">
          {{ scope.row.shopName }}
        </template>
      </el-table-column>
      <el-table-column label="商品主图" align="center">
        <template slot-scope="scope">
          <img :src="scope.row.shopImg" width="50px" height="50px" />
        </template>
      </el-table-column>
      <el-table-column label="商品价格" align="center">
        <template slot-scope="scope">
          {{ scope.row.shopPrice }}
        </template>
      </el-table-column>
      <el-table-column label="商品状态" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status == 1" type="primary">上架</el-tag>
          <el-tag v-if="scope.row.status == 2" type="info">下架</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.updateTime }}
        </template>
      </el-table-column>
      <el-table-column
        class-name="status-col"
        label="操作"
        align="center"
        width="150"
      >
        <template slot-scope="scope">
          <el-link type="warning" @click="goodsave(scope.row.id)">编辑</el-link> |
          <el-link type="primary" @click="goodfind(scope.row.id)">查看</el-link> |
          <el-link type="danger" @click="goodDel(scope.row.id)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <el-drawer
      ref="drawer"
      title="编辑商品"
      :visible.sync="drawerSave"
      :wrapperClosable="false"
      :show-close="false"
      :close-on-press-escape="false"
    >
      <div class="drawer__content" style="height: 800px; overflow: auto">
        <el-form ref="formSave" :model="formSave" label-width="80px" :rules="rules">
          <el-form-item label="商品名称" prop="shopName">
            <el-input v-model="formSave.shopName"></el-input>
          </el-form-item>
          <el-form-item label="一级分类" prop="primaryClass">
            <el-select
              v-model="formSave.primaryClass"
              placeholder="请选择商品一级分类"
              @change="primaryClassCharge"
            >
              <el-option
                :label="item.name"
                :value="item.value"
                v-for="(item, index) in PrimaryClass"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="二级分类" prop="secondaryClass">
            <el-select
              v-model="formSave.secondaryClass"
              placeholder="请选择商品二级分类"
            >
              <el-option
                :label="item.name"
                :value="item.value"
                v-for="(item, index) in SecondaryClass"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品介绍" prop="shopLabel">
            <el-input type="textarea" v-model="formSave.shopLabel"></el-input>
          </el-form-item>
          <el-form-item label="商品主图" prop="shopImg">
            <el-upload
              class="avatar-uploader"
              :action="uploadApi"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="formSave.shopImg"
                :src="formSave.shopImg"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="商品价格" prop="shopPrice">
            <el-input v-model="formSave.shopPrice"></el-input>
          </el-form-item>
          <el-form-item label="轮播图">
            <el-upload
              :action="uploadApi"
              list-type="picture-card"
              :on-success="handleLunboSuccess"
              :on-remove="handleLunboRemove"
              :limit="9"
              :on-exceed="HandleExceed"
              :before-upload="beforeAvatarUpload"
              :file-list="LunboImgList"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="介绍图">
            <el-upload
              :action="uploadApi"
              list-type="picture-card"
              :on-success="handleJieShaoSuccess"
              :on-remove="handleJieShaoRemove"
              :limit="9"
              :on-exceed="HandleExceed"
              :before-upload="beforeAvatarUpload"
              :file-list="JieshaoImgList"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit('formSave')">编辑</el-button>
            <el-button @click="resetForm('formSave')">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { getGoodsList, goodsSave, getGoodsFind, goodsDel } from "@/api/goods";
import { getPrimaryClass, getSecondaryClass } from "@/api/goodstype";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
export default {
  components: { Pagination },
  data() {
    return {
      dialogVisible : false,
      uploadApi: `${process.env.VUE_APP_BASE_API}/admin/goodsUpload`,
      drawerSave: false, //编辑弹窗是否展示
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        shopName: "",
        status: "0",
        page: 1,
        limit: 10,
      },
      formSave: {
        id : '',
        shopName: "",
        shopLabel: "",
        shopImg: "",
        shopPrice: "",
        primaryClass: "",
        secondaryClass: "",
        carouseImg : [],
        introduceImg : []
      },
      PrimaryClass: {}, //商品类型一级分类
      SecondaryClass: {}, //商品类型二级分类
      LunboImgList : [],
      JieshaoImgList : [],
      rules: {
        shopName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        shopLabel: [{ required: true, message: '请输入商品介绍', trigger: 'blur' }],
        shopPrice: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        primaryClass: [{  required: true, message: '请选择一级分类', trigger: 'change' }],
        secondaryClass: [{  required: true, message: '请选择二级分类', trigger: 'change' }],
      }
    };
  },
  created() {
    this.getList();
    this.getPrimaryClass();
  },
  methods: {
    goodfind(goods_id){
      //跳转到商品详情页面
      this.$router.push({
        name: "goodsDetail",
        query: { goods_id: goods_id },
      });
    },
    goodDel(goods_id){
      //删除某一个商品
      this.$confirm('确定将该商品删除么?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          goodsDel({goods_id : goods_id}).then(res=>{
            if(res.code == 200){
              this.$message({
                type : 'success',
                message : res.message
              })
              this.listQuery.page = 1
              this.getList()
            }else{
              this.$message({
                type: 'info',
                message: res.message
              });  
            }
          })
        });
    },
    goodsave(id){
      //打开编辑功能
      this.listLoading = true;
      getGoodsFind({goods_id:id}).then(res=>{
        this.listLoading = false
        if(res.code == 200){
          this.formSave = {
            id : res.data.id,
            shopName: res.data.shopName,
            shopLabel: res.data.shopLabel,
            shopImg: res.data.shopImg,
            shopPrice: res.data.shopPrice,
            primaryClass: res.data.primaryClass,
            secondaryClass: res.data.secondaryClass,
            carouseImg : res.data?.carouseImg.split(','),
            introduceImg : res.data?.introduceImg.split(',')
          }
          this.SecondaryClass = {};
          getSecondaryClass({ value: res.data.primaryClass }).then((res) => {
            this.SecondaryClass = res.data;
          });
          this.LunboImgList = this.formSave.carouseImg.map(item=>{
            return {'url' : item}
          })
          this.JieshaoImgList = this.formSave.introduceImg.map(item=>{
            return {'url' : item}
          })
          this.drawerSave = true
        }else{
          this.$message(res.message)
        }
      }).catch((e)=>{
        this.listLoading = false
      })
    },
    onSubmit(formName){
      //编辑接口
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.formSave.shopImg == '' || this.formSave.carouseImg.length == 0 || this.formSave.introduceImg.length == 0){
            this.$message('请将数据填写完整')
            return false;
          }

          this.formSave.carouseImg = this.formSave.carouseImg.join(',')
          this.formSave.introduceImg = this.formSave.introduceImg.join(',')
          goodsSave(this.formSave).then(res=>{
            if(res.code == 200){
              this.$message('编辑成功'),
              this.getList()
              this.drawerSave = false
            }else{
              this.$message({
                message : res.message,
                type : 'error'
              })
            }
          })
        } else {
          this.$message('请将数据填写完整')
          return false;
        }
      });
    },
    resetForm(formName){
      this.$refs[formName].resetFields();
      this.drawerSave = false
    },
    HandleExceed(){
      this.$message('最多上传9张');
    },
    handleLunboRemove(file){
      //删除轮播图
      if(file.url){
        let index = this.LunboImgList.indexOf(file.url)
        this.formSave.carouseImg.splice(index,1)
        this.LunboImgList.splice(index,1)
      }else{
        let url = file.response.data.url
        let index = this.formSave.carouseImg.indexOf(url)
        this.formSave.carouseImg.splice(index,1)
      }
    },
    handleJieShaoRemove(file){
      //删除介绍图
      if(file.url){
        let index = this.JieshaoImgList.indexOf(file.url)
        this.formSave.introduceImg.splice(index,1)
        this.JieshaoImgList.splice(index,1)
      }else{
        let url = file.response.data.url
        let index = this.formSave.introduceImg.indexOf(url)
        this.formSave.introduceImg.splice(index,1)
      }
    },
    handleLunboSuccess(res,file){
      //轮播图
      this.formSave.carouseImg.push(res.data.url)
    },
    handleJieShaoSuccess(res,file){
      //介绍图
      this.formSave.introduceImg.push(res.data.url)
    },
    primaryClassCharge(e) {
      this.SecondaryClass = {};
      this.formSave.secondaryClass = "";
      getSecondaryClass({ value: e }).then((res) => {
        this.SecondaryClass = res.data;
      });
    },
    beforeAvatarUpload(file) {
      const isJPG = (file.type === "image/jpeg" || file.type === "image/png");
      const isLt2M = file.size / 1024 / 1024 < 1;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是JPG格式或PNG格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 1MB!");
      }
      return isJPG && isLt2M;
    },
    handleAvatarSuccess(res, file) {
      //商品主图上传成功后的处理
      this.formSave.shopImg = res.data.url;
    },
    getPrimaryClass() {
      //获取商品一级分类
      getPrimaryClass().then((res) => {
        this.PrimaryClass = res.data;
      });
    },
    clickAdd(){
      //新增弹窗
      this.formSave = {
        id : '',
        shopName: "",
        shopLabel: "",
        shopImg: "",
        shopPrice: "",
        primaryClass: "",
        secondaryClass: "",
        carouseImg : [],
        introduceImg : []
      },
      this.LunboImgList = []
      this.JieshaoImgList = []
      this.drawerSave = true
    },
    getList() {
      //获取商品列表
      this.listLoading = true;
      getGoodsList(this.listQuery)
        .then((response) => {
          this.list = response.data.list;
          this.total = response.data.total;
          this.listLoading = false;
        })
        .catch((err) => {
          this.listLoading = false;
        });
    },
    onScretSubmit(){
      //查询
      this.listQuery.page = 1
      this.getList();
    },
    onReset() {
      //重置
      this.listQuery = {
        shopName: "",
        status: "0",
        page: 1,
        limit: 10,
      };
      this.getList();
    },
  },
};
</script>

<style scoped lang="scss">
.search-box {
  padding-bottom: 10px;
}

.drawer__content ::-webkit-scrollbar {
  display: none;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>